var express = require('express');
var router = express.Router();
var process = require('child_process');
var os = require('os');
var http = require('http');
var config = require('../routes/config');
var nodemailer = require('nodemailer');
var https = require('https');
var qs = require('querystring');
var mysql = require('mysql');
var transporter = nodemailer.createTransport({
    //https://github.com/andris9/nodemailer-wellknown#supported-services 支持列表
    service: 'qq',
    port: 465, // SMTP 端口
    secureConnection: true, // 使用 SSL
    auth: {
        user: '1012898968@qq.com',
        //这里密码不是qq密码，是你设置的smtp密码
        pass: 'bzbmchyhxkbkbdhi'
    }
});
var mailOptions = {
    from: '1012898968@qq.com', // 发件地址
    to: 'jjl_2009_hi@163.com', // 收件列表
    subject: 'FPS Server 注册验证', // 标题
    //text和html两者只支持一种
    text: '注册验证', // 标题
    html: '<a href="http://127.0.0.1:4003/">点击确定注册</a>' // html 内容
};
var db={};
db.addUser = function(TABLENAME,EMAIL,PASSWD,NAME,callback){
    var connection = mysql.createConnection({
        host:config.mysql.IP,
        user:config.mysql.USER,
        password:config.mysql.PASSWD,
        database:config.mysql.ACCOUNT_DB
    });
    connection.connect();
    var sql = 'INSERT INTO `'+TABLENAME+"`(EMAIL,PASSWD,NAME) VALUES('" + EMAIL + "','" +PASSWD+ "','"+ NAME+"')";
    console.log(sql);
    connection.query(sql,function(err,result){
        if (err) throw err;
        callback(result);
    });
    connection.end();
};

router.post('/name', function(req, res, next) {
    if (req.body.NAME.length < 6) {
        res.render('login',{
            links:config.linkmenu,
            index:config.link.INDEX.link,
            login:req.session.login,
            re:true,
            message:"用户名名字长度必须大于等于6，请重新填写!",
        });
        return;
    }
    if ( req.body.PASSWORD !=  req.body.REPASSWORD)
    {
        res.render('login',{
            links:config.linkmenu,
            index:config.link.INDEX.link,
            login:req.session.login,
            re:true,
            message:"密码不一致，请重新填写!",
        });
        return;
    }
    
    // 去数据库查找数据
    config.checkUserSqlite3(req.body.NAME,function(result){
       if (result) {
        res.render('login',{
            links:config.linkmenu,
            index:config.link.INDEX.link,
            login:req.session.login,
            re:true,
            message:"用户名已经存在，请重新填写!",
        });
        return;
       } 
       else
       {
           config.addUserSqlite3(req.body.NAME,req.body.PASSWORD,function(){
                req.session.login = true;
                var o = {};
                o.name = req.body.USERNAME;
                o.passwd = req.body.PASSWD;
                req.session.userinfo=o;
                res.render('index',{
                    links:config.linkmenu,
                    index:config.link.INDEX,
                    login:req.session.login
                });
            });
       }
    });
});

router.post('/', function(req, res, next) {
    var str = req.body.PASSWORD + "+" + req.body.REPASSWORD + "+" + req.body.NAME + "+" + req.body.NAME + "+" + req.body.EMAIL + "+"+ req.body.TELEPHONE + (new Date().getTime());
    var b = new Buffer(str).toString('base64');
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
    if (!reg.test(req.body.EMAIL)) {
        res.render('login',{
            links:config.linkmenu,
            index:config.link.INDEX.link,
            login:req.session.login,
            re:true,
            message:"邮箱格式不正确，请重新填写!",
        });
        return ;
    }
    if ( req.body.PASSWORD !=  req.body.REPASSWORD)
    {
        res.render('login',{
            links:config.linkmenu,
            index:config.link.INDEX.link,
            login:req.session.login,
            re:true,
            message:"密码不一致，请重新填写!",
        });
        return;
    }
    // 去数据库查询信息
    // 验证邮箱
    config.checkUser("LOGINUSER_DATA","EMAIL='" + new Buffer(req.body.EMAIL).toString('base64')+"'",function(result){
        console.log(result);
        var err = true;
        if (result && result.length == 0)
        {
             err = false;
        }
        if (err)
        {
            // 出错了
            res.render('login',{
                links:config.linkmenu,
                index:config.link.INDEX.link,
                login:req.session.login,
                re:true,
                message:"邮箱已经存在!",
            });
            return ;
        }
        else
        {
            db.addUser("LOGINUSER_DATA",new Buffer(req.body.EMAIL).toString('base64'),new Buffer(req.body.REPASSWORD).toString('base64'),new Buffer("").toString('base64'),function(result){
               console.log(result.affectedRows);
                if (result.affectedRows != 1)
                {
                    res.render('login',{
                        links:config.linkmenu,
                        index:config.link.INDEX.link,
                        login:req.session.login,
                        re:true,
                        message:"用户注册失败!",
                    });
                    return ;
                }
                else
                {
                    console.log("角色注册信息:" +b);

                    mailOptions.html =  '<a href="'+config.link.INDEX+'/register/ver?xx='+b+'">点击确定注册</a>';
                    mailOptions.to = req.body.EMAIL;
                    // 注册系统 向redis 保存当前数据加上时间戳 并存储相关信息
                    // 生成连接发送到用户邮箱 等待用户点击确定 返回到登录界面
                    transporter.sendMail(mailOptions, function(error, info){
                        if(error){
                            return console.log(error);
                        }
                        console.log('Message sent: ' + info.response);
                        res.render('error',{
                            links:config.linkmenu,
                            index:config.link.INDEX.link,
                            login:req.session.login,
                            message:"请登录邮箱查看邮件并点击确定注册",
                        });
                    });
                }
            });

        }
    });

});


router.get('/ver',function(req,res,next){
    console.log("邮件验证" + req.query.xx); //register/ver?name=xxx:key=base64
    // 通过key 获取 user 并且验证通过 填充相关信息
    // redis 存储 name,key,passwd,vertype
    var reginfo = new Buffer(req.query.xx, 'base64').toString();
    if (reginfo)
    {
        // 分离字符串 得到用户信息
        var arr = reginfo.toString().split("+");
        if (arr.length != 6)
        {
            res.render('error',{
                links:config.linkmenu,
                index:config.link.INDEX.link,
                login:req.session.login,
                message:"验证失败",
            });
            return;
        }
        else {
            var o = {};
            o.name = arr[4];
            o.passwd = arr[0];
            console.log(o.name);
            config.checkUser("LOGINUSER_DATA","EMAIL='" + new Buffer(o.name).toString('base64')+"' AND PASSWD='" +new Buffer(o.passwd).toString('base64')+ "'",function(result) {
                if (!result || result.length !=1) {
                    res.render('error', {
                        links: config.linkmenu,
                        index: config.link.INDEX.link,
                        login: req.session.login,
                        message: "密码或者用户名错误",
                    });
                }
                else
                {
                    config.updateUserVer("LOGINUSER_DATA","EMAIL='" + new Buffer(o.name).toString('base64')+"'",function(result){
                        if (result.affectedRows != 1) {
                            res.render('error', {
                                links: config.linkmenu,
                                index: config.link.INDEX.link,
                                login: req.session.login,
                                message: "验证失败",
                            });
                        }
                        else
                        {
                            req.session.login = true;
                            var o = {};
                            o.name = req.body.USERNAME;
                            o.passwd = req.body.PASSWD;
                            req.session.userinfo=o;
                            res.render('index',{
                                links:config.linkmenu,
                                index:config.link.INDEX,
                                login:req.session.login
                            });
                        }

                    });

                }

            });
        }
    }
});


var apikey = 'd2af32add79aa9ae756b4d5ee8a69fc6';
// 修改为您要发送的手机号码，多个号码用逗号隔开
var mobile = '15921393511';
// 修改为您要发送的短信内容
var text = '您的注册链接 打开此链接确定注册成功';
// 指定发送的模板编号
var tpl_id = 1861124;
// 指定发送模板的内容
var tpl_value =  {'#time#':'2007-0630','#content#':'成功注册'};
// 语音短信的内容
var code = '1234';
// 查询账户信息https地址
var get_user_info_uri = '/v2/user/get.json';
// 智能匹配模板发送https地址
var sms_host = 'sms.yunpian.com';
var voice_host = 'voice.yunpian.com';

send_sms_uri = '/v2/sms/single_send.json';
// 指定模板发送接口https地址
send_tpl_sms_uri = '/v2/sms/tpl_single_send.json';
// 发送语音验证码接口https地址
send_voice_uri = '/v2/voice/send.json';

function query_user_info(uri,apikey){
    var post_data = {
        'apikey': apikey,
    };//这是需要提交的数据
    var content = qs.stringify(post_data);
    post(uri,content,sms_host);
}

function send_sms(uri,apikey,mobile,text){
    var post_data = {
        'apikey': apikey,
        'mobile':mobile,
        'text':text,
    };//这是需要提交的数据
    var content = qs.stringify(post_data);
    post(uri,content,sms_host);
}

function send_tpl_sms(uri,apikey,mobile,tpl_id,tpl_value){
    var post_data = {
        'apikey': apikey,
        'mobile':mobile,
        'tpl_id':tpl_id,
        'tpl_value':qs.stringify(tpl_value),
    };//这是需要提交的数据
    var content = qs.stringify(post_data);
    post(uri,content,sms_host);
}
function send_voice_sms(uri,apikey,mobile,code){
    var post_data = {
        'apikey': apikey,
        'mobile':mobile,
        'code':code,
    };//这是需要提交的数据
    var content = qs.stringify(post_data);
    console.log(content);
    post(uri,content,voice_host);
}
function post(uri,content,host){
    var options = {
        hostname: host,
        port: 443,
        path: uri,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };
    var req = https.request(options, function (res) {
        // console.log('STATUS: ' + res.statusCode);
        // console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });
    //console.log(content);
    req.write(content);

    req.end();
}



router.get('/sms',function(req,res,next){
   // query_user_info(get_user_info_uri,apikey);

    //send_sms(send_sms_uri,apikey,mobile,text);

    send_tpl_sms(send_tpl_sms_uri,apikey,mobile,tpl_id,tpl_value);

   // send_voice_sms(send_voice_uri,apikey,mobile,code);
});

module.exports = router;